<?php

namespace App\Http\Controllers\Web;

use App\Models\Products;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ProductsController extends Controller
{
    public function index(Request $request)
    {
        $size = $request->input('size', 10);
        $query = Products::query()->with('productsCategories')->with("projects")->with("buildType");
        $product_id = $request->input("product_id");
        $search_text = $request->input("search_text");
        $category_id = $request->input("category_id");
        $build_type_id = $request->input("build_type_id");

        $query->when($search_text, function ($query) use ($search_text) {
            $query->where('name', "like", "%{$search_text}%");
        });

        $query->when($product_id, function ($query) use ($product_id) {
            $query->where('product_id', $product_id);
        });

        $query->when($category_id, function ($query) use ($category_id) {
            $query->where('category_id', $category_id);
        });

        $query->when($build_type_id, function ($query) use ($build_type_id) {
            $query->where('build_type_id', $build_type_id);
        });

        return $this->successPaginate($query->paginate($size));
    }

    public function requestData(Request $request)
    {
        $requestData = $this->validate($request, [
            'category_id' => 'required',
            'build_type_id' => 'nullable',
            'name' => 'required',
            'name_en' => 'nullable',
            'desc' => 'required',
            'tag' => 'required',
            'img_list' => 'required',
            'introduction' => 'required',
            'usage' => 'required',
            'params' => 'required',
            'desc_en' => 'nullable',
            'tag_en' => 'nullable',
            'introduction_en' => 'nullable',
            'usage_en' => 'nullable',
            'params_en' => 'nullable',
        ]);
        return $requestData;
    }

    public function show($id)
    {
        $product = Products::query()->with('productsCategories')->with("projects")->with("buildType")->findOrFail($id);
        return $this->success($product);
    }

    public function store(Request $request)
    {
        $product = new Products;
        $requestData = $this->requestData($request);
        $product->fill($requestData);
        $product->save();
        return $this->success($requestData);
    }

    public function update(Request $request, $id)
    {
        $product = Products::query()->findOrFail($id);
        $requestData = $this->requestData($request);
        $product->fill($requestData);
        $product->save();
        return $this->success($requestData);
    }

    public function destroy($id)
    {
        $product = Products::query()->findOrFail($id);
        $product->delete();
        return $this->success();
    }
}
